import { Injectable } from '@nestjs/common';
import { ConfigService } from './cus-modules/config/config.service';
import * as sha1 from 'sha1';
import * as https from 'node:https';
import menu from './menu';
import { parseXml } from './utils/xmlTool';
import { WxEventMessage } from './service/wx-event-message.service';

@Injectable()
export class AppService {
  constructor(
    private readonly configService: ConfigService,
    private readonly wxEventMessage: WxEventMessage,
  ) {}

  async validateAsWXServer(
    signature: string,
    timestamp: string,
    nonce: string,
    echostr: string,
  ) {
    const s = [this.configService.get('TOKEN'), timestamp, nonce]
      .sort()
      .join('');

    if (sha1(s) == signature) {
      return echostr + '';
    }

    return 'error';
  }

  async setMenuButton(accessToken): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      const btns = JSON.stringify(menu);

      const requestMe = https.request(
        `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${accessToken}`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json; encoding=utf-8',
            'Content-Length': Buffer.byteLength(btns),
          },
        },
        (res) => {
          res.on('data', (chunk) => {
            const res = JSON.parse(chunk.toString());
            if (res.errcode !== 0) {
              throw new Error('res.errmsg');
            } else {
              console.log('修改菜单成功');
              resolve(res);
            }
          });
          res.on('error', (e) => {
            reject(e);
          });
        },
      );

      requestMe.on('error', (e) => {
        reject(e);
      });

      requestMe.write(btns);
      requestMe.end();
    });
  }

  async replyMessage(body: string): Promise<any> {
    const res = await parseXml(body);
    const {
      ToUserName: toUser,
      FromUserName: fromUser,
      // CreateTime: createTime,
      // MsgId: msgId,
      MsgType: msgType,
      Event: event,
      EventKey: eventKey,
    } = res;
    let msg = '你好';
    if (msgType === 'event') {
      msg = await this.wxEventMessage.handleEvent(res);
    }
    console.log(msgType, event, eventKey);
    const str = Object.entries(res).reduce((t, [k, v], idx) => {
      console.log(idx, t, k, v);
      return t.concat([`${k}: ${v}`]);
    }, []);

    return `<xml>
<ToUserName><![CDATA[${fromUser}]]></ToUserName>
<FromUserName><![CDATA[${toUser}]]></FromUserName>
<CreateTime>${Math.floor(new Date().getTime() / 1000)}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好，\n${msg}]]></Content>
</xml>`;
  }
}
